package njci.softerware.com.myexpress2017.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayList;

import njci.softerware.com.myexpress2017.R;
import njci.softerware.com.myexpress2017.http.HttpClient;
import njci.softerware.com.myexpress2017.http.HttpResponseHandler;
import njci.softerware.com.myexpress2017.serviceObj.ExpressUser;
import njci.softerware.com.myexpress2017.serviceObj.dao.ExpressUserDao;
import njci.softerware.com.myexpress2017.serviceObj.dao.SharedPreferences;
import njci.softerware.com.myexpress2017.utils.Constant;
import okhttp3.FormBody;
import okhttp3.Request;

public class Welcome extends Activity {
    //新建ViewPager实例
    ViewPager pager = null;
    //盛放视图的容器
    ArrayList<View> viewContainter = null;
    Button logInButton = null;
    EditText userName = null;
    EditText userPwd = null;
    Handler handler = null;
    static long millions = 3000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);//去掉信息栏

        setContentView(R.layout.activity_welcome);
        pager = (ViewPager) this.findViewById(R.id.viewpager);
        viewContainter = new ArrayList<View>();
        View view1 = LayoutInflater.from(this).inflate(R.layout.welcome_one, null);
        View view2 = LayoutInflater.from(this).inflate(R.layout.welcome_two, null);
        viewContainter.add(view1);
        viewContainter.add(view2);
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg.arg1 == 1) {
                    pager.setCurrentItem(1);
                    millions=0;
                }

            }
        };
        pager.setAdapter(new PagerAdapter() {

            @Override
            public int getCount() {

                return viewContainter.size();
            }

            //滑动切换的时候销毁当前的组件
            @Override
            public void destroyItem(ViewGroup container, int position,
                                    Object object) {
                ((ViewPager) container).removeView(viewContainter.get(position));
            }

            //每次滑动的时候生成的组件
            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                ((ViewPager) container).addView(viewContainter.get(position));
                return viewContainter.get(position);
            }

            @Override
            public boolean isViewFromObject(View view, Object object) {
                return view == object;
            }

            @Override
            public int getItemPosition(Object object) {
                return super.getItemPosition(object);
            }
        });

        //设置滑动监听
        pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                if (position == 1) {
                    initView();
                }
            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });


        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Message m = new Message();
                m.arg1 = 1;
                handler.sendMessage(m);
            }
        }, millions);
    }


    public void initView() {
        userName = (EditText) findViewById(R.id.user_name);
        userPwd = (EditText) findViewById(R.id.user_pwd);
        logInButton = (Button) findViewById(R.id.login);
        logInButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                String name = userName.getText().toString();
                String pwd = userPwd.getText().toString();
                if (name != null && name.length() > 0 && pwd != null && pwd.length() > 0) {
                    userLogin(name, pwd);
                } else {
                    Toast.makeText(Welcome.this, "登陆失败", Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    public void saveToDb(ExpressUser expressUser) {
        ExpressUserDao userDao = null;
        try {
            userDao = new ExpressUserDao(getApplicationContext());
            if (userDao.getByUserId(expressUser.getId()) == null) {
                userDao.add(expressUser);
            }
            SharedPreferences sh = SharedPreferences.getInstance();
            sh.putInt("userId", expressUser.getId());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void userLogin(String name, String pwd) {
        String url = "http://myexpress2016.carp.mopaasapp.com/serviceUserLogin";
        FormBody formBody = new FormBody.Builder().add("logname", name)
                .add("logpass", pwd)
                .build();
        try {
            HttpClient.post(url, formBody, new HttpResponseHandler() {
                @Override
                public void onSuccess(String content) {
                    if (content != null && !content.contains("error")) {
                        Log.d(Constant.TAG, "onSuccess:" + content);
                        Gson g = new Gson();
                        ExpressUser expressUser = g.fromJson(content, ExpressUser.class);
                        if (expressUser != null) {
                            saveToDb(expressUser);
                            Log.d(Constant.TAG, "成功");
                        }
                        Intent intent = new Intent(Welcome.this, MainActivity.class);
                        startActivity(intent);
                        finish();

                    } else {
                        Log.d(Constant.TAG, "login error:" + content);
                        Toast.makeText(Welcome.this, "登陆失败", Toast.LENGTH_LONG).show();
                    }

                }

                @Override
                public void onFailure(Request request, IOException e) {
                    Log.d(Constant.TAG, "onFailure:" + e.getMessage());
                    Toast.makeText(Welcome.this, "链接服务器失败", Toast.LENGTH_LONG).show();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            Log.d(Constant.TAG, e.getMessage());
        }

    }


}
